package com.wh.base.sys.user.controller;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wh.base.aop.documented.OperLog;
import com.wh.base.sys.role.service.RoleService;
import com.wh.base.sys.user.controller.form.IdForm;
import com.wh.base.sys.user.controller.form.IdsForm;
import com.wh.base.sys.user.controller.form.InsertForm;
import com.wh.base.sys.user.controller.form.SearchListForm;
import com.wh.base.sys.user.controller.form.SearchPageForm;
import com.wh.base.sys.user.controller.form.UpdateForm;
import com.wh.base.sys.user.controller.form.UpdateStatusForm;
import com.wh.base.sys.user.controller.form.resetPwdForm;
import com.wh.base.sys.user.entity.User;
import com.wh.base.sys.user.service.UserService;
import com.wh.base.sys.userRole.entity.UserRole;
import com.wh.base.sys.userRole.service.UserRoleService;
import com.wh.base.util.PwdUtil;
import com.wh.base.util.R;
import com.wh.base.util.RedisUtil;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
import io.swagger.annotations.ApiOperation;

/**
 * <p>
 * 系统用户 前端控制器
 * </p>
 *
 * @author WangHong
 * @since 2022-03-28
 */
@Controller
@RequestMapping("/sys/user")
public class UserController {
	
	@Autowired
	private UserService service;
	
	@Autowired
	private UserRoleService userRoleService;
	
	@Autowired
	private RoleService roleService;
	
	@Resource
    private RedisUtil redisUtil;
	
	@GetMapping("/index")
	@ApiOperation(value = "首页页面")
	@SaCheckPermission("user:view")
	public String index(Model model){
		model.addAttribute("authSign", (Map<String,String>)redisUtil.get("auth_sign_"+StpUtil.getLoginIdAsLong())); //用户权限
		model.addAttribute("roleList", JSONUtil.toJsonStr(roleService.handleRoleList(roleService.list())));
		return "user/index";
	}
	
	@GetMapping("/recycleIndex")
	@ApiOperation(value = "回收站页面")
	@SaCheckPermission("user:recycle")
	public String recycleIndex(Model model){
		model.addAttribute("authSign", (Map<String,String>)redisUtil.get("auth_sign_"+StpUtil.getLoginIdAsLong())); //用户权限
		return "user/recycle";
	}

	@PostMapping("/getPage")
	@ApiOperation(value = "分页查询数据")
	@ResponseBody
	@SaCheckLogin
	public R getPage(@Validated SearchPageForm form){
		Page roadPage = new Page<>(form.getPageNum(), form.getPageSize());
		LambdaQueryWrapper<User> queryWrapper = new QueryWrapper().lambda();
		queryWrapper.eq(User::getDeleteFlag, "0");
		queryWrapper.ne(User::getUsername, "admin");
		if(form.getUsername() != null) {
			queryWrapper.like(User::getUsername, form.getUsername());
		}
		if(form.getRealName() != null) {
			queryWrapper.like(User::getRealName, form.getRealName());
		}
		if(form.getPhone() != null) {
			queryWrapper.like(User::getPhone, form.getPhone());
		}
		if(form.getEmail() != null) {
			queryWrapper.like(User::getEmail, form.getEmail());
		}
		if(form.getStatus() != null) {
			queryWrapper.eq(User::getStatus, form.getStatus());
		}
		Page pageList = service.page(roadPage, queryWrapper);
		
		return R.ok().put("page", service.handlePageRoleList(pageList));
	}

	@PostMapping("/getList")
	@ApiOperation(value = "查询所有数据")
	@ResponseBody
	@SaCheckLogin
	public R getList(@Validated SearchListForm form){
		LambdaQueryWrapper<User> queryWrapper = new QueryWrapper().lambda();
		queryWrapper.eq(User::getDeleteFlag, "0");
		if(form.getUsername() != null) {
			queryWrapper.like(User::getUsername, form.getUsername());
		}
		if(form.getRealName() != null) {
			queryWrapper.like(User::getRealName, form.getRealName());
		}
		if(form.getPhone() != null) {
			queryWrapper.like(User::getPhone, form.getPhone());
		}
		if(form.getEmail() != null) {
			queryWrapper.like(User::getEmail, form.getEmail());
		}
		if(form.getStatus() != null) {
			queryWrapper.eq(User::getStatus, form.getStatus());
		}
		
		List<User> userList = service.list(queryWrapper);
		return R.ok().put("list", service.handleListRoleList(userList));
	}

	@PostMapping("/getRecyclePage")
	@ApiOperation(value = "分页查询回收站数据")
	@ResponseBody
	@SaCheckPermission("user:recycle")
	public R getRecyclePage(@Validated SearchPageForm form){
		Page roadPage = new Page<>(form.getPageNum(), form.getPageSize());
		LambdaQueryWrapper<User> queryWrapper = new QueryWrapper().lambda();
		queryWrapper.eq(User::getDeleteFlag, "1");
		if(form.getUsername() != null) {
			queryWrapper.like(User::getUsername, form.getUsername());
		}
		if(form.getRealName() != null) {
			queryWrapper.like(User::getRealName, form.getRealName());
		}
		if(form.getPhone() != null) {
			queryWrapper.like(User::getPhone, form.getPhone());
		}
		if(form.getEmail() != null) {
			queryWrapper.like(User::getEmail, form.getEmail());
		}
		if(form.getStatus() != null) {
			queryWrapper.eq(User::getStatus, form.getStatus());
		}
		Page pageList = service.page(roadPage, queryWrapper);
		return R.ok().put("page", service.handlePageRoleList(pageList));
	}

	@PostMapping("/getById")
	@ApiOperation(value = "根据id查询数据")
	@SaCheckPermission("user:view")
	@ResponseBody
	public R getById(@Validated IdForm form){
		return R.ok().put("obj", service.handleRoleList(service.getById(form.getId())));
	}

	@PostMapping("/add")
	@ApiOperation(value = "添加数据")
	@SaCheckPermission("user:add")
	@ResponseBody
	@OperLog(operModul = "用户管理", operType = "新增" ,operDesc = "新增用户")
	public R add(@Validated InsertForm form){
		// 检查用户名是否已存在
		QueryWrapper<User> queryWrapper = new QueryWrapper();
		queryWrapper.eq("username", form.getUsername());
		User oldUser = service.getOne(queryWrapper);
		if(oldUser != null) {
			return R.error("用户名已存在");
		}
		// 检查手机号是否存在
		queryWrapper.clear();
		queryWrapper.eq("phone", form.getPhone());
		oldUser = service.getOne(queryWrapper);
		if(oldUser != null) {
			return R.error("手机号已存在");
		}
		
		User user = JSONUtil.parse(form).toBean(User.class);
		user.setCreateTime(new Date());
		user.setCreateUser(service.getUser().getUsername());
		user.setStatus(UserService.USER_STATUS_NORMAL);

		//密码加密
		user.setPassword(PwdUtil.encryptPwd(form.getPassword()));
		boolean flag = service.save(user);
		if(flag) {
			//保存角色
			List<Long> roleIdList = form.roleIdList();
			if(roleIdList != null && roleIdList.size() > 0) {
				for(Long roleId : roleIdList) {
					UserRole ur = new UserRole();
					ur.setUserId(user.getId());
					ur.setRoleId(roleId);
					userRoleService.save(ur);
				}
			}
			return R.ok("添加成功");
		}else{
			return R.error("添加失败");
		}
	}

	@PostMapping("/update")
	@ApiOperation(value = "修改数据")
	@SaCheckPermission("user:update")
	@ResponseBody
	@OperLog(operModul = "用户管理", operType = "修改" ,operDesc = "修改用户")
	public R update(@Validated UpdateForm form){
		// 检查手机号是否与其它已存在用户重复
		QueryWrapper<User> queryWrapper = new QueryWrapper();
		queryWrapper.eq("phone", form.getPhone());
		List<User> usrList = service.list(queryWrapper);
		if(usrList != null && usrList.size() > 0) {
			for(User u : usrList) {
				if(u.getId() != form.getId()) {
					return R.error("手机号与其他用户冲突");
				}
			}
		}
		
		User user = JSONUtil.parse(form).toBean(User.class);
		user.setUpdateTime(new Date());
		user.setUpdateUser(service.getUser().getUsername());
		service.saveOrUpdate(user);
		
		//删除用户所有角色。重新设置
		QueryWrapper<UserRole> wrapper=new QueryWrapper<>();
		wrapper.eq("user_id",form.getId());
		userRoleService.remove(wrapper);
		
		List<Long> roleIdList = form.roleIdList();
		if(roleIdList != null && roleIdList.size() > 0) {
			for(Long roleId : roleIdList) {
				UserRole ur = new UserRole();
				ur.setUserId(user.getId());
				ur.setRoleId(roleId);
				userRoleService.save(ur);
			}
		}
		return R.ok("修改成功");
	}
	
	@PostMapping("/resetPwd")
	@ApiOperation(value = "重置密码")
	@SaCheckPermission("user:resetPwd")
	@ResponseBody
	@OperLog(operModul = "用户管理", operType = "重置密码" ,operDesc = "重置用户密码")
	public R resetPwd(@Validated resetPwdForm form){
		User user = new User();
		user.setPassword(PwdUtil.encryptPwd(form.getPassword()));
		user.setId(form.getId());
		service.saveOrUpdate(user);
		return R.ok("密码重置成功");
	}
	
	@PostMapping("/uptStatus")
	@ApiOperation(value = "修改状态")
	@SaCheckPermission("user:uptStatus")
	@ResponseBody
	@OperLog(operModul = "用户管理", operType = "修改状态" ,operDesc = "修改用户状态")
	public R uptStatus(@Validated UpdateStatusForm form){
		User user = new User();
		user.setStatus(form.getStatus());
		user.setId(form.getId());
		service.saveOrUpdate(user);
		return R.ok("修改成功");
	}
	

	@PostMapping("/restore")
	@ApiOperation(value = "根据ids批量还原回收站的数据")
	@SaCheckPermission("user:recycle")
	@ResponseBody
	@OperLog(operModul = "用户管理", operType = "还原回收站用户" ,operDesc = "还原回收站用户")
	public R restore(@Validated IdsForm form){
		List<Long> idList = form.idList();
		if(idList.size() > 0) {
			List<User> userList = new ArrayList<>();
			for(Long id : idList) {
				User user = new User();
				user.setId(id);
				user.setDeleteFlag("0");
				user.setUpdateTime(new Date());
				user.setUpdateUser(service.getUser().getUsername());
				userList.add(user);
			}
			if(userList.size() > 0) {
				service.saveOrUpdateBatch(userList);
			}
		}
		return R.ok("还原成功");
	}

	@PostMapping("/recycle")
	@ApiOperation(value = "根据id集合将数据放入回收站")
	@SaCheckPermission("user:recycle")
	@ResponseBody
	@OperLog(operModul = "用户管理", operType = "放入回收站" ,operDesc = "将用户放入回收站")
	public R recycle(@Validated IdsForm form){
		List<Long> idList = form.idList();
		if(idList.size() > 0) {
			List<User> userList = new ArrayList<>();
			for(Long id : idList) {
				User user = new User();
				user.setId(id);
				user.setDeleteFlag("1");
				user.setUpdateTime(new Date());
				user.setUpdateUser(service.getUser().getUsername());
				userList.add(user);
			}
			if(userList.size() > 0) {
				service.saveOrUpdateBatch(userList);
			}
		}
		return R.ok("删除成功");
	}

	/**
	 * 删除数据，同步删除用户与角色对应关系
	 * @param form
	 * @return
	 */
	@PostMapping("/delete")
	@ApiOperation(value = "根据id集合彻底删除数据")
	@SaCheckPermission("user:delete")
	@ResponseBody
	@OperLog(operModul = "用户管理", operType = "彻底删除" ,operDesc = "彻底删除用户")
	public R delete(@Validated IdsForm form){
		List<Long> idList = form.idList();
		if(idList.size() > 0) {
			service.removeByIds(idList);
			for(Long id : idList) {
				QueryWrapper<UserRole> queryWrapper = new QueryWrapper<UserRole>();
				queryWrapper.eq("user_id", id);
				userRoleService.remove(queryWrapper);
			}
		}
		return R.ok("删除成功");
	}


}
